package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.entity.AdminButton;
import com.dingreading.cloud.admin.entity.table.AdminButtonTableDef;
import com.dingreading.cloud.admin.mapper.AdminButtonMapper;
import com.dingreading.cloud.admin.service.AdminButtonService;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

import static com.dingreading.cloud.admin.entity.table.AdminRoleButtonTableDef.adminRoleButton;


/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class AdminButtonServiceImpl extends BaseServiceImpl<AdminButtonMapper, AdminButton, AdminButtonTableDef> implements AdminButtonService {

    @Override
    protected AdminButtonTableDef getTable() {
        return AdminButtonTableDef.adminButton;
    }

    @Override
    public Page<AdminButton> pageList(PageUtil pageUtil, String keywords) {
        QueryCondition condition = QueryCondition.createEmpty();
        if (StringUtils.isNotBlank(keywords))
            condition.and(table.name.like(keywords).or(table.remark.like(keywords)));

        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(condition);

        return getMapper().paginate(Page.of(pageUtil.getPage(), pageUtil.getRows()), queryWrapper);
    }

    @Override
    public int dropBean(Long id) {
        QueryWrapper queryWrapper = QueryWrapper.create().where(table.id.eq(id));
        return getMapper().deleteByQuery(queryWrapper);
    }

    @Override
    public List<String> getByRoleId(Long roleId) {
        QueryWrapper where = QueryWrapper.create()
                .select(adminRoleButton.buttonId)
                .from(adminRoleButton)
                .where(adminRoleButton.roleId.eq(roleId));

        QueryWrapper wrapper = QueryWrapper.create()
                .select(table.name)
                .from(table)
                .where(table.id.in(where));

        return getMapper().selectObjectListByQueryAs(wrapper, String.class);
    }

    @Override
    public List<String> listByRoleId(List<Long> roleIds) {
        QueryWrapper where = QueryWrapper.create()
                .select(QueryMethods.distinct(adminRoleButton.buttonId))
                .from(adminRoleButton)
                .where(adminRoleButton.roleId.in(roleIds));

        QueryWrapper wrapper = QueryWrapper.create()
                .select(table.name)
                .from(table)
                .where(table.id.in(where));

        return getMapper().selectObjectListByQueryAs(wrapper, String.class);
    }

    @Override
    public List<AdminButton> getByIds(List<Long> ids) {
        return getMapper().selectListByIds(ids);
    }

}
